<template>
  <div>
    <div class="step"><span>首页</span> > 用户管理 > 用户列表</div>
    <!-- 添加用户部分 -->
    <el-card>
      <el-button class="add" @click="showDialog = true" type="primary"
        >添加用户</el-button
      >

      <!-- 搜索 -->
      <div>
        <el-input
          placeholder="请输入内容"
          v-model="inputVal"
          class="input-with-select"
        >
          <el-button
            @click="search()"
            slot="append"
            icon="el-icon-search"
          ></el-button>
        </el-input>
      </div>
      <!-- prefix-icon="el-icon-search" 该属性可以在input框内添加icon -->
    </el-card>
    <!-- 表格数据 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="#" width="100"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="160">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="170"> </el-table-column>
      <el-table-column prop="mobile" label="电话号" width="180">
      </el-table-column>
      <el-table-column prop="role_name" label="角色" width="150">
      </el-table-column>
      <el-table-column prop="mg_state" label="状态" width="150">
        <template>
          <div>
            <el-switch
              v-model="value"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="todo" label="操作" width="200">
        <template slot-scope="scope">
          <div>
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="mini"
              circle
              @click="editUser(scope.row)"
            >
            </el-button>
            <el-button
              icon="el-icon-delete-solid"
              type="danger"
              size="mini"
              circle
              @click="openDialog(scope.row.id)"
            >
              <!-- scope 是一个特殊的对象，它代表当前行的数据和其他相关信息。
              在这个代码中，scope.$index 表示当前行的索引，即该行数据在表格数据数组中的位置。 -->
            </el-button>
            <el-button
              icon="el-icon-s-tools"
              type="warning"
              size="mini"
              circle
              @click="setting(scope.row)"
            >
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 删除对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="close"
    >
      <img src="../../../assets/notice.png" alt="" />
      <span>此操作将永久删除该用户，是否继续？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAction">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      background
      :current-page="currentPage"
      :total="tableData.length"
      :page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <addDialog :showDialog="showDialog" @close="showDialog = false"></addDialog>
    <editUser
      :showDialog2="showDialog2"
      @close="handleClose"
      :rowData="rowData"
      :selectedId="selectedId"
    ></editUser>
  </div>
</template>

<script>
import request from '../../../utils/request'
import addDialog from '../../../components/dialog/addUser.vue'
import editUser from '../../../components/dialog/editUser.vue'

export default {
  components: { addDialog, editUser },
  beforeRouteEnter (to, from, next) {
    console.log('内置守卫前')
    next()
  },
  // beforeRouteLeave (to, from, next) {
  //   console.log('内置守卫后')
  //   next()
  // },
  mounted () {
    // 渲染用户数据
    this.getUserList()
    console.log(222)
    console.log('mounted阶段')
  },
  data () {
    return {
      tableData: [], // 传参获取，不可以写死
      rowData: {}, // 父传子数据
      selectedId: '', // 存储选中的行的 id
      dialogVisible: false,
      currentId: null,
      value: true,
      form: {
        username: '',
        email: '',
        role_name: '',
        mobile: '',
        mg_state: true
      },
      showDialog: false,
      showDialog2: false,

      formLabelWidth: '120px',
      getInfo: '',
      inputVal: '',
      pageObj: {
        // 分页所需要的参数
        account: '',
        pagenum: 1,
        pagelen: 5 // 每页显示条数
      },
      currentPage: 1,
      pageSize: 5
    }
  },
  methods: {
    getUserList () {
      // 从 sessionStorage 中获取 token
      const data = JSON.parse(sessionStorage.getItem('vuex')) // 获取存储的数据对象
      const token = data.login.token // 获取token字段
      // console.log(token) // 输出token值
      if (token) {
        // 判断token是否存在
        request
          .get('users', {
            headers: {
              Authorization: token // 将 token 添加到请求头中
            },
            params: {
              query: '',
              pagenum: this.pageObj.pagenum,
              pagesize: this.pageObj.pagelen
            }
          })
          .then((res) => {
            console.log(res)
            this.tableData = res.data.users
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
    // 从子组件传来的命令，添加成功，更新列表
    // refreshUserList () {
    //   this.getUserList()
    // },
    search () {
      alert()
    },
    editUser (index) {
      // 获取当前行数据
      this.showDialog2 = true
      console.log(index)
      // 将当前行数据传递给子组件
      this.rowData = { ...index }
      this.selectedId = index.id // 存储选中的行的 id

      // 思路：将列表数据拿到之后传给子组件（父传子），在子组件内填充到input框，
      // 之后点击子组件确定，父组件发起修改请求（子组件内重载页面）
    },
    openDialog (id) {
      // 打开对话框，并设置当前行的 ID
      this.dialogVisible = true
      this.currentId = id
    },
    confirmAction () {
      // 在对话框中点击确定按钮后获取当前行的 ID
      console.log(this.currentId)
      // 删除用户请求
      const uid = this.currentId
      const path = 'users/' + uid
      request.delete(path, {
        id: uid
      })
        .then(res => {
          console.log(res)
          const { data } = res
          if (data.meta.status === 200) {
            this.$message.success('删除成功')
            // 页面重新加载
            window.location.reload()
          } else {
            this.$message.warning('删除失败')
          }
        })
        .catch(err => {
          console.log(err)
        })
      this.dialogVisible = false
    },
    setting () {
      alert()
    },
    handleSizeChange (val) {
      this.pageSize = val
    },
    handleCurrentChange (val) {
      this.currentPage = val
      // 在data中声明变量currentPage，pageSize，分别为默认页，以及默认尺寸。
    },
    handleClose () {
      this.showDialog2 = false
    },
    updateUserList () {
      // 更新用户列表的方法
      this.getUserList()
    },
    close (done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    }
  }
}
</script>

<style scoped lang="scss">
.el-button {
  width: 80px;
  line-height: 30px;
  padding: 0px;
}
.el-card .el-button:nth-of-type(2) {
  float: right;
  width: 40px;
}

.el-card .el-button:nth-of-type(1) {
  /* float: left; */
  /* margin-top: 3px;
  position: absolute;
  left:100px;
  z-index: 999; */
}
.add {
  position: absolute;
  left: 220px;
  top: 20px;
  height: 39px;
}
.el-input {
  float: left;
  width: 200px;
}
.el-card .el-input {
  /* margin-top: -35px; */
}
.el-card .el-input .el-button {
  margin-top: -15px;
  width: 40px;
}
/* table */
.el-table .el-button {
  width: 50px;
}
.is-always-shadow {
  height: 78px;
  margin-top: 0px;
  box-shadow: 0 0px 0 rgba(0, 0, 0) !important;
}
.el-pagination {
  margin-top: 20px;
  text-align: center !important;
}
.step {
  width: 300px;
  height: 40px;
  margin-left: -50px;
  span {
    font-weight: bold;
  }
}
img {
  width: 25px;
  height: 25px;
}
</style>
